package com.example.yxweather.ui.home


import android.os.Handler
import android.os.Looper
import com.example.yxweather.base.BaseInteractor
import com.example.yxweather.util.WeatherUtils
import com.qweather.sdk.Callback
import com.qweather.sdk.QWeather
import com.qweather.sdk.basic.Lang
import com.qweather.sdk.parameter.weather.WeatherParameter
import com.qweather.sdk.response.error.ErrorResponse
import com.qweather.sdk.response.weather.WeatherNowResponse


class HomeInteractor : BaseInteractor<HomeView>() {
    /**
     * 获取当前天气回调接口
     */
    /**
     * 天气数据获取结果回调接口
     * 提供成功与失败两种回调方法
     */
    interface GetWeatherData {
        /**
         * 天气数据获取成功时调用
         * @param response 包含天气信息的响应对象
         */
        fun getWeatherDataSuccess(response: WeatherNowResponse)

        /**
         * 天气数据获取失败时调用
         * @param msg 错误信息描述
         */
        fun getWeatherDataFailed(msg: String)
    }

    /**
     * 1. 获取当前城市天气
     */
    fun getCityCurrentWeather(
        latitude: String,
        longitude: String,
        callback: GetWeatherData
    ) {
        // 1.1 准备参数
        var tempParam =
            WeatherUtils.formatLatLng(longitude) + ',' + WeatherUtils.formatLatLng(latitude)
        var parameter =
            WeatherParameter(tempParam).lang(Lang.ZH_HANS).unit(com.qweather.sdk.basic.Unit.METRIC)

        // 1.2 发起请求
        QWeather.instance.weatherNow(parameter, object : Callback<WeatherNowResponse> {
            override fun onSuccess(response: WeatherNowResponse) {
                // 天气数据请求成功，通过Handler切换到主线程回调接口
                Handler(Looper.getMainLooper()).post {
                    callback.getWeatherDataSuccess(response)
                }
            }

            override fun onFailure(errorResponse: ErrorResponse) {
                // 接口调用失败，获取错误信息并切换到主线程通知UI
                Handler(Looper.getMainLooper()).post {
                    callback.getWeatherDataFailed(errorResponse.toString())
                }
            }

            override fun onException(e: Throwable) {
                // 出现异常，打印异常堆栈信息并通知UI层
                Handler(Looper.getMainLooper()).post {
                    callback.getWeatherDataFailed(e.toString())
                }
                e.printStackTrace()
            }

        })
    }
}